package com.btnc.messageflow.test;

import java.net.URISyntaxException;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.log4j.Logger;

public class MovingNoteListener implements MessageListener {
	private static final Logger logger = Logger
			.getLogger(MovingNoteListener.class);
	private String movingNote;
	
	public String getMovingNote() {
		return movingNote;
	}

	public void setMovingNote(String movingNote) {
		this.movingNote = movingNote;
	}

	public MovingNoteListener(String movingNote){
		setMovingNote(movingNote);
	}
	
	public void onMessage(Message message) {
		TextMessage textMessage = (TextMessage) message;

		try {
			logger.info("received moving note request: "
					+ textMessage.getText());
			ActiveMQConnection connection = ActiveMQConnection
					.makeConnection("tcp://localhost:61616");
			connection.start();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("movingnote.response.input");
			MessageProducer producer = session.createProducer(destination);
			logger.info("Send a moving note back to requesting POS");
			TextMessage movingNote = session.createTextMessage();
			movingNote.setText(this.movingNote);
			producer.send(movingNote);

			connection.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
